from django.shortcuts import render, redirect
from django.views.generic import TemplateView, View
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.contrib.auth import login, logout, authenticate
from django.urls import reverse
from django.contrib.auth.mixins import LoginRequiredMixin
from users.models import Profile
from django.contrib.auth.models import User
from django.shortcuts import render_to_response,HttpResponse


	


# 登录用户
class UserLoginView(TemplateView):
	template_name = 'login.html'
	
	def post(self, request):
		ret = {'status': 0}
		username = request.POST.get('username')
		password = request.POST.get('password')

		if username not in [ p.username for p in User.objects.filter(is_superuser=1) ]:
			#session 中注入权限值
			PermAllow = {}
			pro = Profile.objects.all()
			for pr in pro:
				PermAllow[pr.user.username] = pr.experm

			if username in PermAllow:
				request.session['role_id'] = PermAllow[username]
				request.session.set_expiry(3600)
			else:
				ret['status'] = 1
				ret['msg'] = '账号错误，请重新输入'
				return JsonResponse(ret)

		user = authenticate(username=username, password=password)		
		
		
		if user:			
			login(request, user)
			ret['next_url'] = request.GET.get('next') if request.GET.get('next', None) else '/'
		else:
			ret['status'] = 1
			ret['msg'] = '密码错误,请重新输入'
		
		return JsonResponse(ret)


# 注销用户
class UserLogoutView(LoginRequiredMixin, View):

	def get(self, request):
		logout(request)
		request.session.flush()
		return HttpResponseRedirect(reverse('user_login'))